//
//  EmoticonKBViewController.swift
//  表情键盘
//
//  Created by 雄 on 15/7/20.
//  Copyright © 2015年 雄. All rights reserved.
//

import UIKit

let EmoticonIdentifier = "emoticon_cell"

class EmoticonKBViewController: UIViewController {
    
    /// 闭包 传emoticon
    var didSelectedEmoticonCallBlack: (emoticon: Emoticon) ->()
    // 初始话的时候把 闭包传值
    init(didSelectedEmotion: (emoticon: Emoticon) ->()) {
        
        didSelectedEmoticonCallBlack = didSelectedEmotion
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 表情包模型数据
    lazy var packages: [EmoticonsPackage] = EmoticonsPackage.packages()
    
    // 点击包按钮, 滚动collectionView
    func selectedItem(item: UIBarButtonItem) {
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    override func loadView() {
        super.loadView()
        
        view.backgroundColor = UIColor.blackColor()
        
        prepareUI()
    }
    
    private func prepareUI() {
        view.addSubview(toolBar)
        view.addSubview(collectionView)
        
        // 约束
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[toolBar]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["toolBar": toolBar]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[collectionView]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["collectionView": collectionView]))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[collectionView][toolBar(44)]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["toolBar": toolBar, "collectionView": collectionView]))
    
        prepareCollectionView()
        prepareToolBar()
    }
    
    // collectionView 设置
    private func prepareCollectionView() {
        collectionView.backgroundColor = UIColor.whiteColor()
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.registerClass(MyCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.pagingEnabled = true
        collectionView.bounces = false
    }
    // toolBar 设置
    private func prepareToolBar() {
        var items = [UIBarButtonItem]()
        var index = 0
        for s in packages {
            
            let barBtn = UIBarButtonItem(title: s.groupName, style: UIBarButtonItemStyle.Plain, target: self, action: "selectedItem:")
            barBtn.tag = index
            items.append(barBtn)
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
             index++
        }
        items.removeLast()
        
        toolBar.items = items
        toolBar.tintColor = UIColor.darkGrayColor()
    }
    
    
    // 懒加载
    private lazy var toolBar: UIToolbar = UIToolbar()
    private lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: MyCollectionViewLayout())
    
    // 自定义布局类
    class MyCollectionViewLayout: UICollectionViewFlowLayout {
        override func prepareLayout() {
            super.prepareLayout()
            
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = UICollectionViewScrollDirection.Horizontal
            let w = collectionView!.bounds.width / 7
            itemSize = CGSizeMake(w, w)
            let dh = (collectionView!.bounds.height - w * 3 ) * 0.47
            sectionInset = UIEdgeInsetsMake(dh, 0, dh, 0)
        }
    }
}

/// 源数据方法
extension EmoticonKBViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! MyCollectionViewCell
        
        cell.emoticon = packages[indexPath.section].emoticons![indexPath.item]
        
        return cell
    }
    
    // 点击cell
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! MyCollectionViewCell
        
        let emoticon = cell.emoticon!
        // 添加点击的的表情
        if emoticon.chs != nil || emoticon.emoji != nil {
            emoticon.times++
            packages[0].addNearSelectedEmoticon(emoticon)
        }
        
        // 传值
        didSelectedEmoticonCallBlack(emoticon: emoticon)
    }
    
    
}

/// 自定义cell
class MyCollectionViewCell: UICollectionViewCell {
    
    // 表情模型
    var emoticon: Emoticon? {
        didSet{
            // 关掉按钮交互
            emoticonBtn.userInteractionEnabled = false
            // 设置图片
            if let path = emoticon?.imagePath {
                emoticonBtn.setImage(UIImage(named: path), forState: UIControlState.Normal)
            } else {
                // 防止cell 复用
                emoticonBtn.setImage(nil, forState: UIControlState.Normal)
            }
            
            emoticonBtn.setTitle(emoticon?.emoji ?? "", forState: UIControlState.Normal)
            
            // 设置删除按钮
            if emoticon!.removeBtn {
                emoticonBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoticonBtn.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
            } else {
                emoticonBtn.setImage(nil, forState: UIControlState.Highlighted)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(emoticonBtn)
        emoticonBtn.frame = CGRectInset(bounds, 4, 4)
        emoticonBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var emoticonBtn: UIButton = UIButton()
}



